package com.iflytek.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iflytek.common.Result;
import com.iflytek.dao.CartDao;
import com.iflytek.document.CartDocument;
import com.iflytek.dto.CartDTO;
import com.iflytek.dto.PageDTO;
import com.iflytek.info.Cartinfo;
import com.iflytek.mapper.CartMapper;
import com.iflytek.model.Cart;
import com.iflytek.model.Goods;
import com.iflytek.model.User;
import com.iflytek.service.CartService;
import com.iflytek.service.GoodsService;
import com.iflytek.service.RoleService;
import com.iflytek.service.UserService;
import com.iflytek.utils.CopyUtil;
import com.iflytek.vo.CartVO;
import com.iflytek.vo.GoodsVO;
import com.iflytek.vo.PageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 购物车表 服务实现类
 * </p>
 *
 * @author h_t
 * @since 2023-09-23
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Resource
    private CartMapper cartMapper;
    @Resource
    private CartService cartService;
    @Resource
    private CartDao cartDao;
    @Resource
    private RoleService roleService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private UserService userService;
    /**
     * 查全部
     *
     * @return
     */
    @Override
    public Result<Cartinfo> findAll(HttpServletRequest request) {
        User user = userService.getUserByToken(request);
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(Cart::getUserId,user.getId());
        List<Cart> carts = cartMapper.selectList(wrapper);
        List<CartVO> cartVOS = CopyUtil.copyList(carts, CartVO.class);
        Cartinfo cartinfo = new Cartinfo();



        BigDecimal totalPrice = new BigDecimal("0");
        BigDecimal origPrice = new BigDecimal("0");
        for(CartVO cartVO:cartVOS){
            Long goodsId = cartVO.getGoodsId();
            Goods goods = goodsService.getById(goodsId);
            GoodsVO goodsVO = CopyUtil.copy(goods, GoodsVO.class);
            goodsVO.setRealPrice(goodsVO.getPrice().multiply(BigDecimal.valueOf(goods.getDiscount())));
            cartVO.setGoods(goodsVO);

            totalPrice = totalPrice.add(goodsVO.getRealPrice().multiply(BigDecimal.valueOf(cartVO.getCount())));
            origPrice = origPrice.add(goodsVO.getPrice().multiply(BigDecimal.valueOf(cartVO.getCount())));

        }
        cartinfo.setList(cartVOS);
        cartinfo.setTotalPrice(totalPrice);
        cartinfo.setDiscount(origPrice);
        return Result.success(cartinfo);

    }

    /**
     * 保存
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Boolean> saveCart(CartDTO dto) {
        if (dto == null) {
            return Result.error("1", "内容为空");
        }
        Cart cart = CopyUtil.copy(dto, Cart.class);
        int count = cartMapper.insert(cart);
        if (count > 0) {
            CartDocument copy = CopyUtil.copy(cart, CartDocument.class);
            cartDao.save(copy);
            return Result.success(true);
        } else {
            return Result.error("1", "保存失败");

        }


    }

    /**
     * 更新
     * @param dto
     * @return
     */
    @Override
    public Result<Boolean> updateCart(CartDTO dto) {
        if (dto == null) {
            return Result.error("2", "内容为空");
        }
        Cart cart = CopyUtil.copy(dto, Cart.class);
        int count = cartMapper.updateById(cart);

        if (count > 0) {
            cartDao.deleteById(dto.getId());
            CartDocument copy = CopyUtil.copy(cart, CartDocument.class);
            cartDao.save(copy);
            return Result.success(true);
        } else {
            return Result.error("1", "更新失败");
        }
    }

    /**
     * 查询
     * @param id
     * @return
     */
    @Override
    public Result<CartVO> findById(Long id) {
        Cart cart;
        Optional<CartDocument> cartDocument = cartDao.findById(id);
        CartDocument cartDocument1 = cartDocument.get();
        if (cartDocument1 == null) {
            cart = CopyUtil.copy(cartDocument1, Cart.class);
        } else {
            cart = cartMapper.selectById(id);
        }
        if (id == null) {
            Result.error("401", "id为空");
        }
        CartVO cartVO = CopyUtil.copy(cart, CartVO.class);

        return Result.success(cartVO);
    }


    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public Result<CartVO> deleteById(Long id) {

        if (id == null) {
            Result.error("401", "id为空");
        }
        int i = cartMapper.deleteById(id);

        if (i > 0) {
            cartDao.deleteById(id);
            Result.success();
        } else {

            Result.error("204", "错误");
        }
        return Result.success();
    }

    /**
     * 分页
     *
     * @param dto
     * @return
     */
    @Override
    public Result<PageVO<CartVO>> findPage(PageDTO<CartDTO> dto) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper();

        if (dto.getPageNum() == null) {
            dto.setPageNum(1);
        }
        if (dto.getSize() == null) {
            dto.setSize(5);
        }
        //分页
        PageHelper.startPage(dto.getPageNum(), dto.getSize());

        List<Cart> carts = cartMapper.selectList(queryWrapper);

        List<CartVO> cartVOList = new ArrayList<>();
        cartVOList = CopyUtil.copyList(carts, CartVO.class);

        PageInfo<Cart> cartPageInfo = new PageInfo<>(carts);
        PageVO<CartVO> pageVO = new PageVO<>();
        BeanUtils.copyProperties(dto, pageVO);
        pageVO.setTotal(cartPageInfo.getTotal());
        pageVO.setRecords(cartVOList);
        return Result.success(pageVO);
    }

}

